package com.haixiaoke.saas.workOrder.state.role;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.constant.WorkOrderConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.maintenance.domain.MaintenanceItem;
import com.haixiaoke.saas.house.domain.HousePicture;
import com.haixiaoke.saas.workOrder.domain.WorkOrderPerson;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.workOrder.domain.WorkOrder;
import com.haixiaoke.saas.workOrder.domain.WorkOrderChargeItem;
import com.haixiaoke.saas.workOrder.domain.WorkOrderRecord;
import com.haixiaoke.saas.workOrder.state.server.IWorkOrderTypeServerRole;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 维修单业务服务
 *
 * @author panda
 * @Date 2024/9/3
 **/
public class MaintenanceWorkOrderTypeServerRole extends AbstractSpecificWorkOrderTypeServerRole {
    public MaintenanceWorkOrderTypeServerRole(IWorkOrderTypeServerRole workOrderTypeServerRole) {
        super(workOrderTypeServerRole);
    }

    @Override
    @Transactional
    public int insertWorkOrder(WorkOrder workOrder, String phone) {
        String workOrderId = workOrder.getWorkOrderId();
        Date nowDate = DateUtils.getNowDate();

        //校验故障图片不能超过6张
        if (CollectionUtil.isNotEmpty(workOrder.getFaultPictureList())) {
            if (workOrder.getFaultPictureList().size() > 6) {
                throw new ServiceException("故障照片不能超过6张");
            }
            workOrder.setFaultPicture(StringUtils.join(workOrder.getFaultPictureList(), ","));

            // 插入房屋相册记录
            // 生成分组编号
            String packetIdentification = RandomUtil.randomStringWithoutStr(10, "0123456789");
            addHousePicture(workOrder, "报修申请", packetIdentification);
        }
        if (CollectionUtil.isEmpty(workOrder.getWorkOrderChargeItemList()) ||
                workOrder.getWorkOrderChargeItemList().size() != 1) {
            throw new ServiceException("请选择正确的费用项");
        }

        boolean b = workOrder.getWorkOrderChargeItemList().stream().anyMatch(item -> item.getItemId() == null || StrUtil.isBlank(item.getItemName()));
        if (b) {
            throw new ServiceException("请选择正确的费用项");
        }


        MaintenanceItem maintenanceItem = maintenanceItemService.selectMaintenanceItemByMaintenanceItemId(workOrder.getWorkOrderChargeItemList().get(0).getItemId());
        if (ObjectUtil.isEmpty(maintenanceItem) ||
                !StrUtil.equals(maintenanceItem.getChargeItemType(), WorkOrderConstants.WORK_ORDER_TYPE_MAINTENANCE)) {
            throw new ServiceException("请选择正确的费用项");
        }

        //获取c端用户的id
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(workOrder.getContactsPhone());
        if (ObjectUtil.isEmpty(userConsumer)) {
            userConsumer = new UserConsumer();
            userConsumer.setUserMobile(workOrder.getContactsPhone());
            userConsumer.setUserName(workOrder.getContactsName());
            userConsumer.setLesseeFlag(UserConstants.LESSEE_FLAG_NO);
            userConsumer.setCreateBy(workOrder.getCreateBy());
            userConsumer.setCreateTime(nowDate);
            userConsumerService.insertUserConsumer(userConsumer);
        }

        //插入工单收费项
        workOrder.getWorkOrderChargeItemList().forEach(item -> {
            item.setWorkOrderId(workOrderId);
            item.setCreateTime(nowDate);
            item.setCreateBy(workOrder.getCreateBy());
            item.setHouseId(workOrder.getHouseId());
            item.setTenantId(workOrder.getTenantId());
        });
        workOrderChargeItemService.insertBatchWorkOrderChargeItem(workOrder.getWorkOrderChargeItemList());

        //插入跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord(workOrderId, WorkOrderConstants.RECORD_TYPE_USER_VISIBLE,
                WorkOrderConstants.DISPLAY_TYPE_ORDER_GENERATED, workOrder.getCreateBy() + "（" + phone + "）" + "提交了报修申请", null, null, nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        //插入工单
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_DISPATCH);
        workOrder.setConUserId(userConsumer.getUserId());
        workOrder.setCreateTime(nowDate);
        return workOrderService.insertWorkOrder(workOrder);
    }

    @Override
    public int rejectWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, String userName, String flatUserName) {
        if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_PAY, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_COMPLETED, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_CANCELED, workOrder.getWorkOrderState())) {
            throw new ServiceException("工单状态不正确，无法取消");
        }

        if (StrUtil.isBlank(userName) &&
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE, workOrder.getWorkOrderState())) {
            throw new ServiceException("工单状态不正确，无法取消");
        }

        Date nowDate = DateUtils.getNowDate();
        String operatorInfoStr;
        if (StrUtil.isBlank(userName)) {
            operatorInfoStr = flatUserName;
        } else {
            operatorInfoStr = userName;
        }
        String recordContent = operatorInfoStr + "取消了报修申请，备注：" + workOrderRecord.getRecordContent();
        workOrderRecord.setRecordContent(recordContent);
        workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_CANCELLED);
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_CANCELED);
        workOrder.setUpdateTime(nowDate);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int dispatchWorkOrder(WorkOrder workOrder, WorkOrderPerson workOrderPerson) {
        if (StrUtil.isBlank(workOrder.getDisposeTimeLimit())
                || StrUtil.isBlank(workOrder.getPayer())) {
            throw new ServiceException("处理时限和支付方不能为空");
        }

        if (!StrUtil.equals(WorkOrderConstants.WORK_ORDER_TYPE_MAINTENANCE, workOrder.getWorkOrderType())) {
            throw new ServiceException("选择的工单人员不属于维修员");
        }

        Date nowDate = DateUtils.getNowDate();

        //工单为待派单则插入派单类型的跟进记录,如果为改派则插入没有类型的跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord();
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        workOrderRecord.setReceiverUser(workOrderPerson.getWorkOrderPersonName());
        workOrderRecord.setCreateTime(nowDate);
        if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_DISPATCH, workOrder.getWorkOrderState())) {
            workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
            workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_WAITING_FOR_ACCEPTANCE);
            workOrderRecord.setRecordContent(workOrder.getUpdateBy() + "指派工单给师傅 " + workOrderPerson.getWorkOrderPersonName() +
                    "(" + workOrderPerson.getWorkOrderPersonPhone() + ")");
        } else {
            workOrderRecord.setRecordContent(workOrder.getUpdateBy() + "改派工单给师傅 " + workOrderPerson.getWorkOrderPersonName() +
                    "(" + workOrderPerson.getWorkOrderPersonPhone() + ")");
        }
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setPersonName(workOrderPerson.getWorkOrderPersonName());
        workOrder.setPersonPhone(workOrderPerson.getWorkOrderPersonPhone());
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int receivedWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能接自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能接当前机构的工单");
        }

        Date nowDate = DateUtils.getNowDate();

        WorkOrderRecord wor = new WorkOrderRecord();
        wor.setWorkOrderId(workOrder.getWorkOrderId());
        wor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        wor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_ACCEPTED);
        wor.setReceiverUser(workOrder.getPersonName());
        String recordContent = "师傅" + workOrder.getPersonName() + "已接单";
        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        wor.setRecordContent(recordContent);
        wor.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(wor);

        // 更新工单人员接单时间
        workOrderPersonService.updateWorkOrderPersonLatestOrderTime(personTenantId, busUserId);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        //接单时间
        workOrder.setReceiveOrderTime(nowDate);
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_RECEIVED);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int paymentCompletion(WorkOrder workOrder, WorkOrderRecord record) {

        Date nowDate = DateUtils.getNowDate();
        record.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(record);

        //更新工单状态
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_COMPLETED);
        workOrder.setUpdateTime(nowDate);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int requestRejectionWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        //待接单,已接单,维修中以外的工单不能申请拒接
        if (!(StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_RECEIVED, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE, workOrder.getWorkOrderState()))) {
            throw new ServiceException("工单状态不正确，无法申请拒接、作废");
        }

        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能操作自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能操作当前机构的工单");
        }
        Date nowDate = DateUtils.getNowDate();

        //插入拒单跟进记录
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        String recordContent = "";
        if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING, workOrder.getWorkOrderState())) {
            recordContent = "发起拒接申请，备注：";
        } else if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_RECEIVED, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE, workOrder.getWorkOrderState())){
            recordContent = "发起作废申请，备注：";
        }
        workOrderRecord.setRecordContent("师傅" + workOrder.getPersonName() + "(" + workOrder.getPersonPhone() + ") " +
                recordContent + workOrderRecord.getRecordContent());
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_AUDIT);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int auditDenialWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, String username) {
        Date nowDate = DateUtils.getNowDate();

        WorkOrderRecord wor = new WorkOrderRecord();
        wor.setWorkOrderId(workOrder.getWorkOrderId());
        wor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        wor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_CANCELLED);
        wor.setReceiverUser(workOrder.getPersonName());

        String workOrderState = null;
        String recordContent = username;
        if (StrUtil.equals(workOrderRecord.getAuditDenial(), "1")) {
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_CANCELED;
            recordContent = recordContent + "同意了拒接申请";
        } else if (StrUtil.equals(workOrderRecord.getAuditDenial(), "0")) {
            if (workOrder.getReceiveOrderTime() == null) {
                workOrderState = WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING;
            } else {
                WorkOrderRecord record = workOrderRecordService.selectWorkOrderRecordByRecordTypeAndUserDisplayType(workOrder.getWorkOrderId(),
                        null, WorkOrderConstants.DISPLAY_TYPE_UPLOAD_IMAGE_BEFORE_SERVICE);
                if (ObjectUtil.isEmpty(record)) {
                    workOrderState = WorkOrderConstants.WORK_ORDER_STATE_RECEIVED;
                } else {
                    workOrderState = WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE;
                }
            }
            recordContent = recordContent + "不同意拒接申请";
        }

        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        wor.setRecordContent(recordContent);
        wor.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(wor);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(workOrderState);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int beingRepaired(WorkOrder workOrder) {
        Date nowDate = DateUtils.getNowDate();
        List<WorkOrderRecord> workOrderRecordList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderBeforePictureList())) {
            List<String> newWorkOrderBeforePictureList = new ArrayList<>();
            for (String pictureUrl : workOrder.getWorkOrderBeforePictureList()) {
                if (StrUtil.isBlank(workOrder.getWorkOrderBeforePicture())) {
                    newWorkOrderBeforePictureList = workOrder.getWorkOrderBeforePictureList();
                } else {
                    if (!workOrder.getWorkOrderBeforePicture().contains(pictureUrl)) {
                        newWorkOrderBeforePictureList.add(pictureUrl);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(newWorkOrderBeforePictureList)) {
                String newWorkOrderBeforePictureStr = StringUtils.join(newWorkOrderBeforePictureList, ",");
                WorkOrderRecord beforePictureWor = new WorkOrderRecord();
                beforePictureWor.setWorkOrderId(workOrder.getWorkOrderId());
                beforePictureWor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
                beforePictureWor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_UPLOAD_IMAGE_BEFORE_SERVICE);
                beforePictureWor.setReceiverUser(workOrder.getPersonName());
                beforePictureWor.setRecordContent("师傅已将服务前拍照图片上传至平台");
                beforePictureWor.setRecordImg(newWorkOrderBeforePictureStr);
                beforePictureWor.setCreateTime(nowDate);
                workOrderRecordList.add(beforePictureWor);

                workOrder.setWorkOrderBeforeTime(nowDate);
            }
            String workOrderBeforePictureStr = StringUtils.join(workOrder.getWorkOrderBeforePictureList(), ",");
            workOrder.setWorkOrderBeforePicture(workOrderBeforePictureStr);
        } else {
            workOrder.setWorkOrderBeforePicture("");
        }

        if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderAfterPictureList())) {
            List<String> newWorkOrderAfterPictureList = new ArrayList<>();
            for (String pictureUrl : workOrder.getWorkOrderAfterPictureList()) {
                if (StrUtil.isBlank(workOrder.getWorkOrderAfterPicture())) {
                    newWorkOrderAfterPictureList = workOrder.getWorkOrderAfterPictureList();
                } else {
                    if (!workOrder.getWorkOrderAfterPicture().contains(pictureUrl)) {
                        newWorkOrderAfterPictureList.add(pictureUrl);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(newWorkOrderAfterPictureList)) {
                String newWorkOrderAfterPictureStr = StringUtils.join(newWorkOrderAfterPictureList, ",");
                WorkOrderRecord afterPictureWor = new WorkOrderRecord();
                afterPictureWor.setWorkOrderId(workOrder.getWorkOrderId());
                afterPictureWor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
                afterPictureWor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_UPLOAD_IMAGE_AFTER_SERVICE);
                afterPictureWor.setReceiverUser(workOrder.getPersonName());
                afterPictureWor.setRecordContent("师傅已将服务后拍照图片上传至平台");
                afterPictureWor.setRecordImg(newWorkOrderAfterPictureStr);
                afterPictureWor.setCreateTime(nowDate);
                workOrderRecordList.add(afterPictureWor);

                workOrder.setWorkOrderAfterTime(nowDate);
            }
            String workOrderAfterPictureStr = StringUtils.join(workOrder.getWorkOrderAfterPictureList(), ",");
            workOrder.setWorkOrderAfterPicture(workOrderAfterPictureStr);
        } else {
            workOrder.setWorkOrderAfterPicture("");
        }

        if (CollectionUtil.isNotEmpty(workOrderRecordList)) {
            workOrderRecordService.insertBatchWorkOrderRecord(workOrderRecordList);
        }



        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE);

        int result = workOrderService.updateWorkOrder(workOrder);
        if (result > 0) {
            //删除维修费用项
            workOrderChargeItemService.deleteWorkOrderChargeItemByWorkOrderId(workOrder.getWorkOrderId());
            //插入维修费用项
            for (WorkOrderChargeItem workOrderChargeItem : workOrder.getWorkOrderChargeItemList()) {
                workOrderChargeItem.setWorkOrderId(workOrder.getWorkOrderId());
                workOrderChargeItem.setHouseId(workOrder.getHouseId());
                workOrderChargeItem.setCreateTime(nowDate);
                workOrderChargeItem.setCreateBy(workOrder.getUpdateBy());
                workOrderChargeItem.setTenantId(workOrder.getTenantId());
            }
            workOrderChargeItemService.insertBatchWorkOrderChargeItem(workOrder.getWorkOrderChargeItemList());
        }


        // 插入房屋相册记录
        HousePicture sqlHousePicture = housePictureService.selectHousePictureByWorkOrderId(workOrder.getWorkOrderId());
        if (ObjectUtil.isEmpty(sqlHousePicture)) {
            // 生成分组编号
            String packetIdentification = RandomUtil.randomStringWithoutStr(10, "0123456789");
            if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderBeforePictureList())) {
                addHousePicture(workOrder, "报修前", packetIdentification);
            }
            if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderAfterPictureList())) {
                addHousePicture(workOrder, "报修后", packetIdentification);
            }
        } else {
            if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderBeforePictureList())) {
                addHousePicture(workOrder, "报修前", sqlHousePicture.getPacketIdentification());
            }
            if (CollectionUtil.isNotEmpty(workOrder.getWorkOrderAfterPictureList())) {
                addHousePicture(workOrder, "报修后", sqlHousePicture.getPacketIdentification());
            }
        }


        return result;
    }

    private void addHousePicture(WorkOrder workOrder, String processName, String packetIdentification) {
        HousePicture housePicture = new HousePicture(workOrder.getHouseId(), workOrder.getPremisesAddress(), HouseConstants.HOUSE_PICTURE_REPAIRS, workOrder.getCreateBy(),
                workOrder.getOperatorId(), workOrder.getFaultPicture().split(",").length, workOrder.getFaultPicture(), workOrder.getTenantId(),
                processName, null, workOrder.getWorkOrderId(), packetIdentification);
        housePictureService.insertHousePicture(housePicture);
    }


    @Override
    @Transactional
    public int submitPaymentSlip(WorkOrder workOrder) {
        Date nowDate = DateUtils.getNowDate();
        //工单金额
        BigDecimal workOrderAmount = BigDecimal.ZERO;
        List<WorkOrderChargeItem> workOrderChargeItemList = workOrderChargeItemService.selectWorkOrderChargeItemByWorkOrderId(workOrder.getWorkOrderId());
        for (WorkOrderChargeItem item : workOrderChargeItemList) {
            //材料费*数量+劳务费
            BigDecimal chargeSum = item.getMaterialCost().multiply(item.getChargeQuantity()).add(item.getLaborCost());
            workOrderAmount = workOrderAmount.add(chargeSum);
        }
        //工单状态
        String workOrderState = null;

        List<WorkOrderRecord> workOrderRecordList = new ArrayList<>();
        WorkOrderRecord wor = new WorkOrderRecord();
        wor.setWorkOrderId(workOrder.getWorkOrderId());
        wor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        wor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_PENDING_PAYMENT);
        wor.setReceiverUser(workOrder.getPersonName());
        wor.setRecordContent("师傅已将服务费用提交至平台");
        wor.setCreateTime(nowDate);
        workOrderRecordList.add(wor);

        int result = workOrderAmount.compareTo(BigDecimal.ZERO);
        if (result > 0) {
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_WAIT_PAY;
        } else if (result == 0) {
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_COMPLETED;
            WorkOrderRecord workOrderRecord = new WorkOrderRecord();
            workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
            workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
            workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_COMPLETED);
            workOrderRecord.setReceiverUser(workOrder.getPersonName());
            workOrderRecord.setRecordContent(workOrder.getContactsName() + "已完成");
            workOrderRecord.setCreateTime(nowDate);
            workOrderRecordList.add(workOrderRecord);
        }
        workOrderRecordService.insertBatchWorkOrderRecord(workOrderRecordList);

        //更新工单
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(workOrderState);
        workOrder.setWorkOrderAmount(workOrderAmount);
        workOrder.setWorkCompletedTime(nowDate);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int revocationRejectionWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能操作自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能操作当前机构的工单");
        }
        Date nowDate = DateUtils.getNowDate();

        //插入拒单跟进记录
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        String recordContent = "师傅" + workOrder.getPersonName() + "（" + workOrder.getPersonPhone() + "）撤销拒接申请";
        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        workOrderRecord.setRecordContent(recordContent);
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        //接单时间
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int updateWorkOrder(WorkOrder workOrder, String phone) {
        Date nowDate = DateUtils.getNowDate();

        //校验故障图片不能超过6张
        if (CollectionUtil.isNotEmpty(workOrder.getFaultPictureList())) {
            if (workOrder.getFaultPictureList().size() > 6) {
                throw new ServiceException("故障照片不能超过6张");
            }
            workOrder.setFaultPicture(StringUtils.join(workOrder.getFaultPictureList(), ","));
        } else {
            workOrder.setFaultPicture("");
        }
        if (CollectionUtil.isEmpty(workOrder.getWorkOrderChargeItemList()) ||
                workOrder.getWorkOrderChargeItemList().size() != 1) {
            throw new ServiceException("请选择正确的费用项");
        }

        //获取c端用户的id
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(workOrder.getContactsPhone());
        if (ObjectUtil.isEmpty(userConsumer)) {
            userConsumer = new UserConsumer();
            userConsumer.setUserMobile(workOrder.getContactsPhone());
            userConsumer.setUserName(workOrder.getContactsName());
            userConsumer.setLesseeFlag(UserConstants.LESSEE_FLAG_NO);
            userConsumer.setCreateBy(workOrder.getUpdateBy());
            userConsumer.setCreateTime(nowDate);
            userConsumerService.insertUserConsumer(userConsumer);
        }

        //插入工单收费项
        workOrderChargeItemService.deleteWorkOrderChargeItemByWorkOrderId(workOrder.getWorkOrderId());
        workOrder.getWorkOrderChargeItemList().forEach(item -> {
            item.setWorkOrderId(workOrder.getWorkOrderId());
            item.setCreateTime(nowDate);
            item.setCreateBy(workOrder.getUpdateBy());
            item.setHouseId(workOrder.getHouseId());
            item.setTenantId(workOrder.getTenantId());
        });
        workOrderChargeItemService.insertBatchWorkOrderChargeItem(workOrder.getWorkOrderChargeItemList());

        //插入跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord(workOrder.getWorkOrderId(), WorkOrderConstants.RECORD_TYPE_USER_VISIBLE,
                WorkOrderConstants.DISPLAY_TYPE_ORDER_MODIFIED, workOrder.getContactsName() + "(" + phone
                + ")" + "修改了报修申请", null, null, nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        // 插入房屋相册记录
        HousePicture sqlHousePicture = housePictureService.selectHousePictureByWorkOrderId(workOrder.getWorkOrderId());
        if (ObjectUtil.isEmpty(sqlHousePicture)) {
            // 生成分组编号
            String packetIdentification = RandomUtil.randomStringWithoutStr(10, "0123456789");
            addHousePicture(workOrder, "报修申请", packetIdentification);
        } else {
            HousePicture housePicture = new HousePicture(workOrder.getHouseId(), workOrder.getPremisesAddress(), HouseConstants.HOUSE_PICTURE_REPAIRS, workOrder.getUpdateBy(),
                    workOrder.getOperatorId(), workOrder.getFaultPicture().split(",").length, workOrder.getFaultPicture(), sqlHousePicture.getTenantId(),
                    "报修申请", null, workOrder.getWorkOrderId(), sqlHousePicture.getPacketIdentification());
            housePicture.setHousePictureId(sqlHousePicture.getHousePictureId());
            housePictureService.updateHousePicture(housePicture);
        }

        //编辑工单
        workOrder.setConUserId(userConsumer.getUserId());
        workOrder.setUpdateTime(nowDate);
        return workOrderService.updateWorkOrder(workOrder);
    }
}
